/*
 * @Author: lee
 * @Date: 2024-01-15 09:39:24
 * @LastEditors: lee
 * @LastEditTime: 2024-01-16 18:08:24
 * @Description: file content
 */
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
  }
}

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    // authUser:{}
  },

  mutations: {
    SET_TOKEN: (state, data) => {
      state.token = data;
    },
    SET_NAME: (state, data) => {
      state.name = data;
    },
    SET_AVATAR: (state, data) => {
      state.avatar = data;
    },
    SET_ROLES: (state, data) => {
      state.roles = data;
    },
    SET_USER(state, user) {
      state.authUser = user;
    },
    LOG_OUT(state) {
      // state.token = ''
      Object.assign(state, getDefaultState())
    }
  },
  actions: {
    setToken({ commit }, data) {
      commit('SET_TOKEN', data)
      setToken(data)
    },
    setName({ commit }, data) {
      commit('SET_NAME', data)
    },
    setAvatar({ commit }, data) {
      commit('SET_AVATAR', data)
    },
    setRoles({ commit }, data) {
      commit('SET_ROLES', data)
    },
    logOUt({ commit }) {
      return new Promise((resolve, reject) => {
        try {
          commit('LOG_OUT')
          removeToken()
          resolve()
        } catch (error) {
          reject(error)
        }
      })

    }
    // nuxtServerInit({ commit }, { req }) {
    //   if (req.session && req.session.userid) {
    //     console.log("用户已经登录");
    //     commit("SET_USER", req.session.userid);
    //   }
    // },
  }
};

export default user;
